import React from 'react';
import {Row, Col, Tabs, Table, Icon, Input, Button, message} from 'antd';

import DicListModalContainer from '../Modal/DicListModalContainer';
import DicInfoModalContainer from '../Modal/DicInfoModalContainer';
import SubEditCell from '../EditCell/SubEditCell';

import {colBindDic} from "../../services/dictionaryServer";
import {updateTableMeta, updateRemCom} from "../../services/showServer";

import Signals from 'signals';

import styles from './table.less';

const TabPane = Tabs.TabPane


class ShowEditTableComponent extends React.Component {
  constructor(props) {
    super(props);
    //signals事件
    this.signal = new Signals.Signal();

    this.state = {
      remark: '',
      comment: '',
      editComment: '',
      searchText: '',
      filterDropdownVisible: false,
      partitionColumns: [],
      columnsFilter: [],
      columns: [],
      tableMeta: null,
      table: null,
    };
  }

  componentWillMount() {
    this.signal.add(function (bind) {
      colBindDic(bind).then(function (res) {
        // 绑定成功后刷新页面数据
        if (res.status == 200) {
          this.props.listSignal.dispatch(this.state.table.id);
        } else {
          message.error('关联字典表失败', 2.5);
        }
      }.bind(this));
    }.bind(this));
  }

  getTime(ver) {
    var date = new Date(Number(ver));
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
  }

  fileSize(size) {
    if (!size) {
      return
    }

    var kb = 1024;
    var mb = kb * 1024;
    var gb = mb * 1024;

    if (size >= gb) {
      var f = (size / gb).toFixed(2);
      return f.toString() + "GB";
    } else if (size >= mb) {
      var f = (size / mb).toFixed(2);
      return f.toString() + "MB";
    } else if (size >= kb) {
      var f = (size / kb).toFixed(2);
      return f.toString() + "KB";
    } else
      return size.toString() + "B";
  }

  onInputChange(e) {
    this.setState({
      searchText: e.target.value
    });
  }

  onFilterDropdownVisibleChange(visible) {
    this.setState({
      filterDropdownVisible: visible
    });
  }

  onSearch() {
    const {searchText, columnsFilter} = this.state;
    const reg = new RegExp(searchText, 'gi');
    this.setState({
      filterDropdownVisible: false,
      columns: columnsFilter.map((record) => {
        const match = record.name.match(reg);
        if (!match) {
          return null;
        }
        return {
          ...record,
        };
      }).filter(record => !!record),
    });
  }

  onCellChange = (index, key) => {
    return (value) => {
      const columns = [...this.state.columns];
      const name = columns[index]['name'];

      //更新后的表元数据
      var metaJson = this.state.tableMeta;
      //更新后的列信息
      for (var c in metaJson.columns) {
        if (metaJson.columns[c].name == name) {
          metaJson.columns[c].remark = value
        }
      }

      //整体更新数据库
      var requstData = {
        "id": this.state.table.id,
        "tableMeta": JSON.stringify(metaJson)
      }

      updateTableMeta(requstData).then(function (res) {
        //更新成功后刷新页面元数据
        if (res.status == 200) {
          this.setState({
            tableMeta: JSON.stringify(metaJson)
          });
        } else {
          message.error('更新分类失败', 2.5);
        }
      }.bind(this));

    };
  }

  handleRemarkChange(e) {
    this.setState({
      remark: e.target.value,
    });
  }

  handleCommentChange(e) {
    this.setState({
      editComment: e.target.value,
    });
  }

  dicBindClick(record) {
    var tableId = this.state.table.id
    var cname = record.name
    // console.log("q:" + tableId + "/" + cname)
    this.refs.dicList.setState({
      tableId: tableId,
      cname: cname,
      visible: true,
    });
  }

  dicClick(record) {
    var dicId = record.dicId
    this.refs.dicInfo.setState({
      visible: true,
    });
    this.refs.dicInfo.initItems(dicId)
  }

  updateRemCom() {
    var requstData = {
      "id": this.state.table.id,
      "remark": this.state.remark,
      "comment": this.state.editComment
    }
    updateRemCom(requstData).then(function (res) {
      //更新成功后刷新List数据
      if (res.status == 200) {
        this.setState({
          comment: this.state.editComment,
        });
        var listData = {
          "id": this.state.table.id,
          "comment": this.state.comment
        }
        this.props.commentSignal.dispatch(listData);
      } else {
        message.error('更新表信息失败', 2.5);
      }
    }.bind(this));
  }

  render() {
    const {partitionColumns, columns} = this.state;

    const col_pagination = {
      total: columns.length,
      showSizeChanger: true,
    };

    const par_pagination = {
      total: partitionColumns.length,
      showSizeChanger: true,
    };

    const col_columns = [{
      title: '列名',
      key: 'name',
      dataIndex: 'name',
      width: '15%',
      filterDropdown: (
        <div className={styles.custom_filter_dropdown}>
          <Input
            placeholder=""
            value={this.state.searchText}
            onChange={this.onInputChange.bind(this)}
            onPressEnter={this.onSearch.bind(this)}
          />
          <Button type="primary" onClick={this.onSearch.bind(this)}>查询</Button>
        </div>
      ),
      filterDropdownVisible: this.state.filterDropdownVisible,
      onFilterDropdownVisibleChange: this.onFilterDropdownVisibleChange.bind(this),
    }, {
      title: '数据类型',
      key: 'type',
      dataIndex: 'type',
      width: '10%',
    }, {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark',
      render: (text, record, index) => (
        <SubEditCell
          value={text}
          onChange={this.onCellChange(index, 'remark')}
        />
      ),
    }, {
      title: '字典',
      key: 'dicId',
      dataIndex: 'dicId',
      width: '10%',
      render: (text, record, index) => {
        return (
          text != null ?
            (
              text != null ?
                (
                  <div>
                    <Button type="primary" shape="circle" size="small" style={{border: 0}}
                            onClick={this.dicBindClick.bind(this, record)}>
                      <Icon style={{color: '#F0F0F0'}} type="link"/>
                    </Button>
                    <Button type="primary" shape="circle" size="small" style={{background: '#87D068', border: 0}}
                            onClick={this.dicClick.bind(this, record)}>
                      <Icon style={{color: '#F0F0F0'}} type="tags"/>
                    </Button>
                  </div>
                ) :
                (
                  <Button type="primary" shape="circle" size="small" style={{border: 0}}
                          onClick={this.dicBindClick.bind(this, record)}>
                    <Icon style={{color: '#F0F0F0'}} type="link"/>
                  </Button>
                )
            ) :
            (
              <Button type="primary" shape="circle" size="small" style={{border: 0}}
                      onClick={this.dicBindClick.bind(this, record)}>
                <Icon style={{color: '#F0F0F0'}} type="link"/>
              </Button>
            )
        );
      },
    }];

    const par_columns = [{
      title: '分区名',
      key: 'name',
      dataIndex: 'name',
    }, {
      title: '数据类型',
      key: 'type',
      dataIndex: 'type',
    }];

    const TableInfo = table => {
      if (table == null) {
        return <div></div>;
      } else {
        return (
          <div>
            <p></p>
            <Row>
              <Col span={4} style={{textAlign: "right"}}>表名：</Col>
              <Col span={20}>{this.state.table.name}</Col>
            </Row>
            <p></p>
            <Row>
              <Col span={4} style={{textAlign: "right"}}>管理员：</Col>
              <Col span={20}>{this.state.table.managerName}</Col>
            </Row>
            <p></p>
            <Row>
              <Col span={4} style={{textAlign: "right"}}>表说明：</Col>
              <Col span={20}>{this.state.comment}</Col>
            </Row>
            <p></p>
            <p></p>
            <Tabs defaultActiveKey="0">
              <TabPane tab="表信息" key="0">
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>表别名：</Col>
                  <Col span={16}>
                    <Input id="remark" value={this.state.remark} onChange={this.handleRemarkChange.bind(this)}/>
                  </Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>管理员：</Col>
                  <Col span={16}>{this.state.table.managerName}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>物理地址：</Col>
                  <Col span={16}>{this.state.tableMeta.location}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>拥有者：</Col>
                  <Col span={16}>{this.state.tableMeta.owner}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>最小文件大小：</Col>
                  <Col span={16}>{this.fileSize(this.state.tableMeta.minFileSize)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>最大文件大小：</Col>
                  <Col span={16}>{this.fileSize(this.state.tableMeta.maxFileSize)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>总文件大小：</Col>
                  <Col span={16}>{this.fileSize(this.state.tableMeta.totalFileSize)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>总文件数：</Col>
                  <Col span={16}>{this.state.tableMeta.totalNumberFiles}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>最近更新时间：</Col>
                  <Col span={16}>{this.getTime(this.state.tableMeta.lastUpdateTime)}</Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={4} style={{textAlign: "right"}}>表说明：</Col>
                  <Col span={16}>
                    <Input id="comment" type="textarea" rows={4} defaultValue={this.state.comment}
                           value={this.state.editComment}
                           onChange={this.handleCommentChange.bind(this)}/>
                  </Col>
                  <Col span={4} style={{textAlign: "right"}}></Col>
                </Row>
                <p></p>
                <Row>
                  <Col span={12} offset={4}>
                    <Button type="primary" onClick={this.updateRemCom.bind(this)}>保存</Button>
                  </Col>
                  <Col span={8} style={{textAlign: "right"}}></Col>
                </Row>
              </TabPane>

              <TabPane tab="列信息" key="1">
                <Row>
                  <Col span={24}>
                    <Table bordered size="middle" columns={col_columns} pagination={col_pagination}
                           dataSource={columns} rowKey={record => record.name}/>
                  </Col>
                </Row>
              </TabPane>

              <TabPane tab="分区信息" key="2">
                <Row>
                  <Col span={24}>
                    <Table bordered size="middle" columns={par_columns} pagination={par_pagination}
                           dataSource={partitionColumns} rowKey={record => record.name}/>
                  </Col>
                </Row>
              </TabPane>
            </Tabs>
            <DicListModalContainer ref="dicList" signal={this.signal}></DicListModalContainer>
            <DicInfoModalContainer ref="dicInfo"></DicInfoModalContainer>
          </div>
        );
      }
    };

    const tableInfo = TableInfo(this.state.table);

    return (
      <div>
        {tableInfo}
      </div>
    );
  }
}

export default ShowEditTableComponent;

